var app = angular.module('myApp', ['ngSanitize', 'ngAnimate']);

app.directive('fileUploader', function($http) {
    return {
        restrict: 'AE',
        scope: {
            url: '=url',
            file: '=file',
            show: '=show'
        },
        template: '<form id="uf" action="{{url}}" method="post" enctype="multipart/form-data"><div class="iis" ng-show="show"><div class="lt1"><div class="i"><span>{{name}}</span></div></div>' +
        '<div class="lt2"><a href="javascript:void(0)"><input type="hidden" name="keep" value="1"><input class="ff" name="firmware" type="file" accept="application/octet-stream">浏览</a></div>' +
        '<div ng-show="save" style="margin:10px auto;"><input type="button" class="btn" value="提交"></div></div></form>',
        link: function(scope, element, attributes) {
            scope.save = false;
            $(element).find(".lt1 .i").on('click', function() {
                $(element).find(".ff").trigger('click');
            })
            $(element).find(".ff").on('change', function() {
                changeFile();
            });
            $(element).find(".btn").on('click',function () {
                var form = document.getElementById('uf');
                formData = new FormData(form);
                $.ajax({
                    url: scope.url,
                    type: "post",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (result) {
                        if (result.code == 0) {
                            utils.loadingWithheight(300000, 250, $("#uploading").html());
                        } else {
                            utils.alert(result.msg)
                        }
                    },
                    error: function (err) {
                        utils.alert("网络连接失败,稍后重试");
                    }
                })
            });
            var changeFile = function() {
                scope.name = $(element).find(".ff")[0].files[0].name;
                scope.file = $(element).find(".ff")[0].files[0];
                scope.save = true;
                scope.$apply();
            }
            scope.$watch('file', function(n, o) {
                if (n == null) {
                    scope.save = false;
                    scope.name = "请选择升级文件";
                    scope.show = false;
                }
            })
            scope.saveFile = function() {
            }
            scope.name = '请选择升级文件';
        }
    }
})